package com.iamteer.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.tomcat.util.descriptor.web.LoginConfig;

import com.iamteer.service.IAdminService;
import com.iamteer.service.impl.AdminService;
import com.iamteer.entity.Admin;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/admin")
public class AdminServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private IAdminService adminService = new AdminService();
	
	private String uri;
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String method = request.getParameter("method");
		if ("login".equals(method)) {
			login(request, response);
		} else if("logout".equals(method)) {
			logout(request,response);
		}
	}

	private void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession();
		if (session != null) {
			session.invalidate();
		}
		response.sendRedirect(request.getContextPath() + "/login.jsp");
	}

	private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		// 1. 获取参数
		String userName = request.getParameter("userName");
		String pwd = request.getParameter("pwd");
		// 封装
		Admin admin = new Admin();
		admin.setUserName(userName);
		admin.setPwd(pwd);
		
		try {
			// 2. 调用 service 处理业务
			Admin loginInfo = adminService.findByNameAndPwd(admin);
			if (loginInfo == null) {
				// 登录失败
				uri = "/login.jsp";
			} else {
				// 登录成功
				// 先保存数据到session
				request.getSession().setAttribute("loginInfo", loginInfo);
				// [在线列表：]
				// 1. 先从 ServletContext 中拿到在线列表集合；（onelineList）
				// 2. 当前用户放入“在线列表集合中”
				ServletContext sc = getServletContext();
				List<Admin> onlineList = (List<Admin>) sc.getAttribute("onlineList");
				if (onlineList != null) {
					onlineList.add(loginInfo);
				}
				
				// 再跳转到首页显示 servlet(/index)
				uri = "/index";
//				uri = "/online.jsp";
			}
		} catch (Exception e) {
			// 测试
			e.printStackTrace();
			// 错误
			uri = "/error/error.jsp";
		}
		// 3. 跳转
		request.getRequestDispatcher(uri).forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
